package com.saifan.wyy_ov.ui.property;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.alipay.AlipayResult;
import com.saifan.alipay.AlipayUtils;
import com.saifan.wxpay.WXPayUtils;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.AdvanceBean;
import com.saifan.wyy_ov.data.bean.PayResultBean;
import com.saifan.wyy_ov.data.bean.RoomInfoBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.communitycenter.PaythefeesActivity;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.BootstrapButton;
import com.saifan.wyy_ov.ui.view.MaterialDialog;
import com.saifan.wyy_ov.utils.DialogUtil;
import com.saifan.wyy_ov.utils.ToastUtil;
import com.saifan.wyy_ov.wxapi.WXPayEntryActivity;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import net.sourceforge.simcpux.Constants;

import java.util.List;

/**
 * @version V1.0.0
 * @author: lomasky
 * @date: 2015-5-27 11:22:55
 * @descrption 缴费
 */

public class CostPayActivity extends BaseActivity {
    private Toolbar toolbar;
    private android.widget.EditText amount;
    private com.saifan.wyy_ov.ui.view.BootstrapButton paybutton;
    RoomInfoBean roomInfoBean;
    private android.widget.TextView address;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView();


    }


    public void setContentView() {
        setContentView(R.layout.activity_cost_pay);
        this.address = (TextView) findViewById(R.id.address);
        roomInfoBean = (RoomInfoBean) getIntent().getSerializableExtra(RoomInfoBean.class.getSimpleName());
        this.paybutton = (BootstrapButton) findViewById(R.id.pay_button);
        this.amount = (EditText) findViewById(R.id.amount);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        this.address.setText(roomInfoBean.getXMDA_XMMC()+roomInfoBean.getWYFJDA_FJMC());
        setPricePoint(amount);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        paybutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(amount.getText().toString()))
                    ToastUtil.showToast(CostPayActivity.this, "请输入预缴金额");
                else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(CostPayActivity.this);
                    builder.setTitle("选择支付类型");
                    builder.setItems(new String[]{"微信支付", "支付宝支付"}, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                            creatPay(i);
                        }
                    });
                    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
                        @Override
                        public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
                            switch (keyCode) {
                                case 4:
                                    dialogInterface.dismiss();
                                    break;
                                default:
                                    break;
                            }
                            return true;
                        }
                    });
                    builder.show();
                }
            }
        });
    }

    private void creatPay(final int type) {
        AdvanceBean advanceBean = new AdvanceBean();
        advanceBean.setFJMC(roomInfoBean.getWYFJDA_FJMC());
        advanceBean.setFJWJ(roomInfoBean.getWYFJDA_ZJ());
        advanceBean.setFKGXWJ(roomInfoBean.getFKGX_ZJ());
        advanceBean.setJFLX(String.valueOf(type));
        advanceBean.setKHWJ(roomInfoBean.getWYKHDA_ZJ());
        advanceBean.setXMBS(String.valueOf(roomInfoBean.getXMBS()));
        advanceBean.setYZXM(roomInfoBean.getWYKHDA_KHMC());
        advanceBean.setYJJE(amount.getText().toString());
        new GetData().getDataJson(CostPayActivity.this, Api.Cost.ADVANCE, advanceBean, "正在请求...", new ResponseData() {
            @Override
            public void onSuccess(String json) {
                if (type == 1) {
                    List<PayResultBean> list = (new Gson()).fromJson(json, new TypeToken<List<PayResultBean>>() {
                    }.getType());
                    if (list != null) {
                        AlipayUtils alipayUtils = new AlipayUtils();
                        alipayUtils.alipay(CostPayActivity.this, list.get(0).getPrepay_id(), new AlipayResult() {
                            @Override
                            public void onResult(int code) {
                                Intent intent = new Intent(CostPayActivity.this, WXPayEntryActivity.class);
                                intent.putExtra("pay_result", code);
                                startActivity(intent);
                            }
                        });
                    } else {
                        ToastUtil.showToast(CostPayActivity.this, "服务器出错了 !");
                    }
                } else {
                    List<PayResultBean> list = (new Gson()).fromJson(json, new TypeToken<List<PayResultBean>>() {
                    }.getType());
                    if (list != null) {
                        Constants.API_KEY = list.get(0).getKey();
                        Constants.APP_ID = list.get(0).getAPPID();
                        Constants.MCH_ID = list.get(0).getMCHID();
                        WXPayUtils wxPayUtils = new WXPayUtils();
                        if (!wxPayUtils.isWXAppInstalledAndSupported(CostPayActivity.this, WXAPIFactory.createWXAPI(CostPayActivity.this, null))) {

                            final MaterialDialog dialog= DialogUtil.createDailog(CostPayActivity.this,"提示","您尚未安装微信");
                            dialog.setNegativeButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                    dialog.dismiss();
                                }
                            });
                            dialog.show();
                            return;
                        }
                        wxPayUtils.sendPayReq(CostPayActivity.this, list.get(0).getPrepay_id());
                    } else {
                        ToastUtil.showToast(CostPayActivity.this, "服务器出错了 !");
                    }
                }

            }

            @Override
            public void onFailed(String str) {

            }
        });
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_pay, menu);
//        return true;
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        int id = item.getItemId();
//        if (id == R.id.action_settings) {
//            startActivity(PaythefeesActivity.class);
//            return true;
//        }
//
//        return super.onOptionsItemSelected(item);
//    }

    public static void setPricePoint(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });

    }
}
